#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#define NUM 5
typedef void (*fun_t)();
fun_t tasks[NUM];



//验证进程等待话题，验证已成功
//////////////////////////任务/////////////////////////////
void printlog()
{
    printf("this is log print task\n");
}
void printNet()
{
    printf("this is s Net print task\n");
}
void printNPC()
{
    printf("this is a flush NPC\n");
}


void init_tasks()
{
    tasks[0]  = printlog;
    tasks[1]  = printNet;
    tasks[2] = printNPC;
    tasks[3] = NULL;
}
void excute_task()
{
    for(int i = 0;tasks[i];i++)//一种回调机制
    {
        tasks[i]();
    }
}
int main()
{
    init_tasks();
    pid_t id = fork();
    if(id == 0)
    {
        //child
        int cnt = 5;
        while(cnt)
        {
            printf("I am child: pid:%d ppid: %d cnt:%d\n",getpid(),getppid(),cnt);
            sleep(1);
           // int * p = NULL;
           // *p =  10;
            cnt--;
        }
        sleep(1);
        exit(100);
    }
    int status = 0;
    while(1)
    {
        //轮询是等待验证
        pid_t rid = waitpid(id,&status,WNOHANG);//WNOHANG为轮询阻塞等待
        if(rid > 0)
        {
            //此情况说明：等待成功，子进程已经退出
            printf("wait succcess ,rid:%d  , status: %d, exit code: %d\n",rid, status,WEXITSTATUS(status));
            break;//等待成功退出循环不再查询
        }
        else if(rid == 0)
        {
            //waitpid返回0 说明：子进程还没有退出
            //printf("father process : child process is runing ,do other thing \n");
            printf("------------------任务开始--------------------\n");
            excute_task();
            printf("------------------任务结束--------------------\n");

        }
        else
        {
         perror("waitpid");
         break;
        }
        sleep(1);
    }
    //pid_t rid = waitpid(id,&status,0);//父进程等待回收子进程，得到退出码，和退出信号
    //if(rid > 0)//当rid > 0 时表示父进程回收成功
    //{
    //    if(WIFEXITED(status))
    //    {

    //     // printf("wait success ,rid:%d status:%d ,exit sign:%d ,exit code:%d\n",rid,status,status&0x7F,(status>>8)&0xFF);//从退出status中得到退出码 和退出信号
    //     
    //      printf("wait success ,rid:%d status:%d , exit code:%d\n",rid,status,WEXITSTATUS(status));//从退出status中得到退出码 和退出信号
    //   }
    //    else 
    //    {
    //        printf("child process error\n");
    //    }
    //    }
    return 0;
}








































//int main()
//{
//   pid_t id =  fork();
//   if(id == 0)
//   {
//     //child
//     int cnt = 5;
//     while(cnt)
//     {
//         printf("Child is runing, pid: %d ; ppid: %d\n",getpid(),getppid());
//         sleep(1);
//         cnt--;
//     }
//     exit(1);
//   }
//   //father
//   int status = 0;
//   pid_t rid = waitpid(id,&status,0);
//   if(rid>0)
//   {
//       printf("wait success,rif:%d status:%d\n",rid,status);
//   }
//   sleep(3);
//
//
//    return 0;
//}
